package com.etrans.web.gps.common.message;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.etrans.web.gps.common.http.HttpClient;
import com.etrans.web.gps.common.http.JSONUtil;
import com.etrans.web.gps.common.http.Response;

/**
 * 短信通知类
 * @author jw.chen
 *
 */
public abstract class SMSUtil {
	/*
	 * webservice服务器定义
	 */
	 // 我们所有的Demo，都是在GBK环境下测试的。
	 //调用注册方法可能不成功。
	 //java.io.IOException: Server returned HTTP response code: 400 for URL: http://sdk105.entinfo.cn/webservice.asmx。
	 //如果出现上述400错误，请参考第102行。
	 //如果您的系统是utf-8，收到的短信可能是乱码，请参考第290行
	static String serviceURL = "";
	static String sn = "SDK-SZW-010-00009";// 序列号
	static String password = "f@a367@4";
	static String pwd = "";// 密码
	public static String DRIVER_MSG_MODULE_ID = "DRIVER_APP";
	@Value("${MESSAGE_SENDER_TYPE}")
	private static String messageSenderType;
	private static boolean flag = false;          //默认是用新版短信发送



	private static String MESSAGE_SEND_TYPE_OLE = "MESSAGE_SEND_TYPE_OLE";
	@SuppressWarnings("unused")
	private static String MESSAGE_SEND_TYPE_NEW= "MESSAGE_SEND_TYPE_NEW";

	/*老短信发动连接配置*/
	private static String SERVICE_URL_OLD = "http://sdk105.entinfo.cn/webservice.asmx";
	private static String SN_OLD = "SDK-SZW-010-00009";// 序列号
	private static String PSWD_OLD = "f@a367@4";


	/*新短信发动连接配置*/
	private static String SERVICE_URL_NEW = "http://api.esoftsms.com/msg/HttpBatchSendSM";
	private static String PSWD_NEW = "SDK0787";
	private static String ACCOUNT  = "SDK0787";
	private static String NEEDSTATUS = "true";
	private static String RESPTYPE = "json";

	public static String PREFIX = "【】短信通知：";


	private static Logger log = LoggerFactory.getLogger(SMSUtil.class);

	static {
		if(SMSUtil.MESSAGE_SEND_TYPE_OLE.equals(messageSenderType)){
			flag = false;
		}
	}


	/*
	 * 方法名称：mt 
	 * 功    能：发送短信 ,传多个手机号就是群发，一个手机号就是单条提交
	 * 参    数：mobile,content,ext,stime,rrid(手机号，内容，扩展码，定时时间，唯一标识)
	 * 返 回 值：唯一标识，如果不填写rrid将返回系统生成的
	 */
	public  static String mt(String mobile, String content, String ext, String stime,String rrid){
		log.info("短信发送，接口模板：{}，手机号：{}，验证码：{}", flag ? "神州" : "webservice", mobile, content);
		if(flag){
			return mt_new(mobile, content, ext, stime, rrid);
		} else {
			return mt_old(mobile, content, ext, stime, rrid);

		}
	}


	/*
    * 方法名称：mt
    * 功    能：发送短信 ,传多个手机号就是群发，一个手机号就是单条提交
    * 参    数：mobile,content,ext,stime,rrid(手机号，内容，扩展码，定时时间，唯一标识)
    * 返 回 值：唯一标识，如果不填写rrid将返回系统生成的
    */
	public static String mt_old(String mobile, String content, String ext, String stime, String rrid) {

		String pwd = SMSUtil.getMD5(SMSUtil.SN_OLD + SMSUtil.PSWD_OLD);
		System.out.print("==================================================================");
		System.out.println(String.format("sn=%s,password=%s,pwd=%s",SMSUtil.SN_OLD,SMSUtil.PSWD_OLD,pwd));

		String result = "";
		String soapAction = "http://tempuri.org/mt";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
		xml += "<soap:Body>";
		xml += "<mt xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + SMSUtil.SN_OLD + "</sn>";
		xml += "<pwd>" + pwd + "</pwd>";
		xml += "<mobile>" + mobile + "</mobile>";
		xml += "<content>" +  SMSUtil.PREFIX +content + "</content>";
		xml += "<ext>" + ext + "</ext>";
		xml += "<stime>" + stime + "</stime>";
		xml += "<rrid>" + rrid + "</rrid>";
		xml += "</mt>";
		xml += "</soap:Body>";
		xml += "</soap:Envelope>";
		System.out.println("xml = " + xml);
		URL url;
		try {
			url = new URL(SMSUtil.SERVICE_URL_OLD);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			//bout.write(xml.getBytes());
			//如果您的系统是utf-8,这里请改成
			bout.write(xml.getBytes("GBK"));

			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern.compile("<mtResult>(.*)</mtResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "100";
		}
	}


	/*
	 * 方法名称：mt
	 * 功    能：发送短信 ,传多个手机号就是群发，一个手机号就是单条提交
	 * 参    数：mobile,content,ext,stime,rrid(手机号，内容，扩展码，定时时间，唯一标识)
	 * 返 回 值：唯一标识，如果不填写rrid将返回系统生成的
	 */
	@SuppressWarnings("unchecked")
	public static String mt_new(String mobile, String content, String ext, String stime, String rrid) {

		String ts = new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis());

        /*密码为： 账号 + 密码 + 时间戳 的 md5值*/
		String pwd = SMSUtil.getMD5(SMSUtil.ACCOUNT + SMSUtil.PSWD_NEW + ts);
		System.out.print("==================================================================");
		System.out.println(String.format("account=%s,password=%s,pwd=%s,ts=%s",SMSUtil.ACCOUNT,SMSUtil.PSWD_NEW,pwd,ts));
		try {
			HashMap<String, Object> param = new HashMap<>();
			param.put("account"   , SMSUtil.ACCOUNT);
			param.put("ts"        , ts);
			param.put("pswd"      , pwd);
			param.put("mobile"    , mobile);
			param.put("msg"       , SMSUtil.PREFIX + content);
			param.put("needstatus", SMSUtil.NEEDSTATUS);
			param.put("resptype"  , SMSUtil.RESPTYPE);

			Response response  = HttpClient.post(SMSUtil.SERVICE_URL_NEW, param);
			String responseStr = response.asString();
			HashMap<String, Object> respMap = JSONUtil.fromJson(responseStr, HashMap.class);
			Integer code = respMap.get("result") !=null ? Integer.parseInt(respMap.get("result").toString()) : 100;
			return code !=0 ? "100" : "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "100";
		}
	}
	
	
	/*
	 * 方法名称：mt
	 * 功    能：发送短信 ,传多个手机号就是群发，一个手机号就是单条提交
	 * 参    数：mobile,content,ext,stime,rrid(手机号，内容，扩展码，定时时间，唯一标识)
	 * 返 回 值：唯一标识，如果不填写rrid将返回系统生成的
	 */
	public static String sendMessage(String mobile, String content, String ext, String stime, String rrid) {
		String pwd = SMSUtil.getMD5(SMSUtil.SN_OLD + SMSUtil.PSWD_OLD);
		System.out.print("==================================================================");
		System.out.println(String.format("sn=%s,password=%s,pwd=%s",SMSUtil.SN_OLD,SMSUtil.PSWD_OLD,pwd));

		String result = "";
		String soapAction = "http://tempuri.org/mt";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
		xml += "<soap:Body>";
		xml += "<mt xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + SMSUtil.SN_OLD + "</sn>";
		xml += "<pwd>" + pwd + "</pwd>";
		xml += "<mobile>" + mobile + "</mobile>";
		xml += "<content>"+content + "</content>";
		xml += "<ext>" + ext + "</ext>";
		xml += "<stime>" + stime + "</stime>";
		xml += "<rrid>" + rrid + "</rrid>";
		xml += "</mt>";
		xml += "</soap:Body>";
		xml += "</soap:Envelope>";
		System.out.println("xml = " + xml);
		URL url;
		try {
			url = new URL(SMSUtil.SERVICE_URL_OLD);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			//bout.write(xml.getBytes());
			//如果您的系统是utf-8,这里请改成
			bout.write(xml.getBytes("GBK"));

			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern.compile("<mtResult>(.*)</mtResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "100";
		}
	}
	


	/*
	 * 方法名称：getMD5 
	 * 功    能：字符串MD5加密 
	 * 参    数：待转换字符串 
	 * 返 回 值：加密之后字符串
	 */
	public static String getMD5(String sourceStr){
		String resultStr = "";
		try {
			byte[] temp = sourceStr.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(temp);
			// resultStr = new String(md5.digest());
			byte[] b = md5.digest();
			for (int i = 0; i < b.length; i++) {
				char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'A', 'B', 'C', 'D', 'E', 'F' };
				char[] ob = new char[2];
				ob[0] = digit[(b[i] >>> 4) & 0X0F];
				ob[1] = digit[b[i] & 0X0F];
				resultStr += new String(ob);
			}
			return resultStr;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args){
		System.out.println(SMSUtil.sendMessage("18507657258", "【车辆联网联控平台】贵公司车牌【粤AV7376】于[2018-03-13 09:43:01]提示【超速】报警；请核查，谢谢", "", "", ""));
	}

}



